// src/page/LoginPage.tsx
import React, {useContext, useState} from 'react'
import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Checkbox, Form, Input, Card, Typography, message } from 'antd'
import { useNavigate } from 'react-router-dom'
import UserContext from '../context/UserContext.tsx';
import {authService, type LoginRequest} from '../api/service/AuthService'



const { Title } = Typography

const LoginPage: React.FC = () => {
    const [loading, setLoading] = useState(false)
    const navigate = useNavigate()
    const context = useContext(UserContext);


    if (!context) {
        throw new Error('UserContext must be used within UserProvider');
    }

    const { setUserInfo } = context;

    const onFinish = async (values: LoginRequest & { remember: boolean }) => {
        setLoading(true)

        try {
            // 调用 AuthService 进行登录
            const response = await authService.login({
                username: values.username,
                password: values.password
            });

            // 检查是否成功获取用户信息
            if (response.id && response.username) {
                message.success('登录成功')

                // 构造用户信息对象
                const userInfo = {
                    id: response.id,
                    username: response.username,
                    nickname: response.nickname,
                    avatar_addr: response.avatar_addr,
                    status: response.status,
                    create_time: response.create_time,
                    update_time: response.update_time,
                    access_token: response.access_token
                };

                // 保存用户信息到 context（会自动保存到localStorage）
                setUserInfo(userInfo);



                // 登录成功后跳转到主页
                navigate('/dashboard')
            } else {
                message.error('登录失败，请检查用户名和密码')
            }
        } catch (error) {
            console.error('登录错误:', error)
            message.error('登录失败，请稍后重试')
        } finally {
            setLoading(false)
        }
    }

    return (
        <div style={{
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100vw',
            height: '100vh',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            margin: 0,
            padding: 0,
            overflow: 'hidden'
        }}>
            <Card style={{
                width: 'calc(100% - 32px)',
                maxWidth: 400,
                borderRadius: 8,
                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                margin: 16
            }}>
                <div style={{
                    textAlign: 'center',
                    marginBottom: 30,
                    marginTop: 20
                }}>
                    <Title level={3}>管理系统登录</Title>
                </div>

                <Form
                    name="login_form"
                    initialValues={{ remember: true,
                        username: 'userwu',     // 添加默认用户名
                        password: '123456'     // 添加默认密码
                    }}
                    onFinish={onFinish}
                    style={{ padding: '0 24px 24px' }}
                >
                    <Form.Item
                        name="username"
                        rules={[{ required: true, message: '请输入用户名!' }]}
                    >
                        <Input
                            prefix={<UserOutlined />}
                            placeholder="用户名"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: '请输入密码!' }]}
                    >
                        <Input
                            prefix={<LockOutlined />}
                            type="password"
                            placeholder="密码"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item name="remember" valuePropName="checked">
                        <Checkbox>记住我</Checkbox>
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="primary"
                            htmlType="submit"
                            loading={loading}
                            size="large"
                            style={{ width: '100%' }}
                        >
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}

export default LoginPage